# select.py

"""
This module is constructed following the famous example wx-doodle.
"""


import wx			
from pylab import *
from scipy.misc import toimage



def pilToImage(pil):
	image = wx.EmptyImage(pil.size[0], pil.size[1])
	image.SetData(pil.convert('RGB').tostring())
	return image

def imageToBitmap(image):
	return image.ConvertToBitmap()

def pilToBitmap(pil):
	return imageToBitmap(pilToImage(pil))
### funciones tomadas de http://wiki.wxpython.org/index.cgi/WorkingWithImages

#----------------------------------------------------------------------
""" Se calibro midiendo la impresion de 5 letras de cada tipo en mm y dividiendo por 5
y multiplicando por 8"""
def getLetra(letra):
	### medida de width=letra+gap
#	if   letra=='?':t0 =(heigth,width) 
	if   letra=='a':t0 =(05.6, 12.80) 
	elif letra=='b':t0 =(08.72, 10.40)
	elif letra=='c':t0 =(11.90, 14.40)
	elif letra=='d':t0 =(11.52, 14.40)
	elif letra=='e':t0 =(19.20, 22.40)
	elif letra=='f':t0 =(15.36, 19.20)
	elif letra=='g':t0 =(44.00, 48.00)
	elif letra=='h':t0 =(17.73, 19.20)
	elif letra=='gs':t0=(44.60, 48.00)
	
	return t0


class SelectWindow(wx.Window):

	def __init__(self, *args, **kwds):
		
		aux = kwds.pop("image",None)
		shape = kwds.pop("shape",None)
		pos = kwds.pop("pos",None)
		numi = kwds.pop("numi",None)
		tipo = kwds.pop("tipo",None)
		
		
		self.numi=numi
		self.letra=tipo
		self.m1,self.m2=getLetra(self.letra)
		self.m1=self.m1*self.numi


		self.buffer=wx.BitmapFromImage( wx.EmptyImage( shape[1], shape[0] ) )
		self.bmp = pilToBitmap(toimage(aux))

		kwds["style"] = wx.NO_FULL_REPAINT_ON_RESIZE

		wx.Window.__init__(self, *args, **kwds)

		self.cpoint=pos
		aux2=where(aux<0,0,aux)
	
		self.InitBuffer()		
		
		self.SetCursor(wx.StockCursor(wx.CURSOR_PENCIL))

		# hook some mouse events
		self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
		self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
		#~ self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
		
		# the window resize event and idle events for managing the buffer
		self.Bind(wx.EVT_SIZE, self.OnSize)
		self.Bind(wx.EVT_IDLE, self.OnIdle)

		# and the refresh event
		self.Bind(wx.EVT_PAINT, self.OnPaint)

		# When the window is destroyed, clean up resources.
		self.Bind(wx.EVT_WINDOW_DESTROY, self.Cleanup)

	
	
	def resendLetra(self,letra):
		self.letra=str(letra)
		self.m1,self.m2=getLetra(self.letra)
		self.m1=self.m1*self.numi
		self.InitBuffer()
		self.Refresh()
		
	def resendNumi(self,numi):
		print numi
		self.numi=numi
		self.m1,self.m2=getLetra(self.letra)	
		self.m1=self.m1*self.numi


		self.InitBuffer()	
		self.Refresh()
		
	def Cleanup(self, evt):
		if hasattr(self, "menu"):
			self.menu.Destroy()
			del self.menu

	def InitBuffer(self):
		"""Initialize the bitmap used for buffering the display."""
		dc = wx.BufferedDC(None, self.buffer)
		self.DrawPoints(dc)
		self.DrawingBMP(dc)
		
		self.reInitBuffer = False

	def DrawingBMP(self, dc):
		dc.DrawBitmap(self.bmp, 0, 0, True)

 	def OnLeftDown(self, event):
		self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))

	def OnLeftUp(self, event):
		self.p = event.GetPosition()
		self.cpoint=self.p
		self.Refresh()


	def OnSize(self, event):
		"""
		Called when the window is resized.  We set a flag so the idle
		handler will resize the buffer.
		"""
		self.reInitBuffer = True

	def OnIdle(self, event):
		"""
		If the size was changed then resize the bitmap used for double
		buffering to match the window size.  We do it in Idle time so
		there is only one refresh after resizing is done, not lots while
		it is happening.
		"""
		if self.reInitBuffer:
			self.InitBuffer()
			self.Refresh(False)

	def OnPaint(self, event):
		
		dc = wx.BufferedPaintDC(self, self.buffer)
		dc = wx.PaintDC(self)
		self.DrawPoints(dc)	

	def DrawPoints(self, dc):
		if self.cpoint:
			dc.SetPen(wx.Pen('RED', 4))
			point=self.cpoint
			#~ dc.DrawCircle(point.x,point.y, 1) 
			#~ dc.DrawText('00001',point.x, point.y,)
			dc.DrawRectangle(point[0], point[1],self.m1,self.m2)		
			
			
	def cancel(self):
		self.clist=[]
		self.reInitBuffer = True

#----------------------------------------------------------------------

class SelectFrame(wx.Frame):
	def __init__(self, *args, **kwds):
		kwds["style"] = wx.DEFAULT_FRAME_STYLE| wx.NO_FULL_REPAINT_ON_RESIZE
		
		holo=imread('prueba.png')	
		Shape=holo.shape
		
		kwds["size"] = ( Shape[1],Shape[0] )
		wx.Frame.__init__(self, *args, **kwds)
		
		
				 
		select = SelectWindow(self, -1, image=holo,shape=Shape)
		print select.cpoint
		#~ select = SelectWindow(self, -1)		
		#~ select.flag_select='manual'

class MyApp(wx.App):
	def OnInit(self):
		wx.InitAllImageHandlers()
		frame_1 = SelectFrame(None, -1, "Select Frame")
		self.SetTopWindow(frame_1)
		frame_1.Show()
		return 1

if __name__ == "__main__":
	app = MyApp(0)
	app.MainLoop()


